package com.apkcore.core.util

import android.annotation.SuppressLint
import android.app.Activity
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

/**
 * 用于处理点击空白处隐藏键盘
 */
object SoftInputUtils {

    @SuppressLint("ClickableViewAccessibility")
    fun setupTouchEvent(activity: Activity) {
        activity.window.decorView.setOnTouchListener { _, event ->
            if (event.action == MotionEvent.ACTION_DOWN) {
                activity.currentFocus?.let { view ->
                    if (view is EditText && !isInSide(view, event) && isSoftInputDisplayed(activity)) {
                        hideSoftInput(view, activity)
                    }
                }
            }
            false
        }
    }

    private fun isInSide(view: View, event: MotionEvent): Boolean {
        val location = intArrayOf(0, 0)
        view.getLocationInWindow(location)
        val left = location[0]
        val top = location[1]
        val right = left + view.width
        val bottom = top + view.height
        return (event.x >= left && event.x <= right && event.y > top && event.y < bottom)
    }

    private fun isSoftInputDisplayed(activity: Activity): Boolean {
        return ViewCompat.getRootWindowInsets(activity.window.decorView)
            ?.isVisible(WindowInsetsCompat.Type.ime()) ?: false
    }

    fun hideSoftInput(view: View, activity: Activity) {
        view.clearFocus()
        val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }
}
